package location

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"fmt"
	imgtype "github.com/shamsher31/goimgtype"
	"image/jpeg"
	"io"
	"log"
	"os"
	"sync"

	"io/ioutil"
	"strings"
)

//根据目录获取所以图片
func GetImgsByPath(root string)  ([]string,error) {

	var files []string

	if !IsDir(root) {
		return files,errors.New(root+"不录不存在或者无法访问")
	}

	fileInfo,err := ioutil.ReadDir(root)
	if err != nil {
		fmt.Println("读取目录"+root+"出错",err.Error())
		return nil,errors.New("读取目录出错")
	}
	var wg sync.WaitGroup
	for _, info := range fileInfo {
		wg.Add(1)
		go func(name string) {
			file := root+"\\"+name
			if IsImgFile(file) {
				files = append(files,file)
			}
			wg.Done()
		}(info.Name())

	}
	wg.Wait()

	if err != nil {
		return files,err
	}

	return files,nil
}

//是否为图片文件
func IsImgFile(fileName string) bool {
	if IsDir(fileName) {
		return false
	}
	_, err2 := imgtype.Get(fileName)
	if err2 != nil {
		return false;
	} else {
		return true;
	}
}

//是否是目录
func IsDir(fileAddr string)bool{
	s,err:=os.Stat(fileAddr)
	if err!=nil{
		log.Println(err)
		return false
	}
	return s.IsDir()
}

//获取文件大小
func GetSize(filepath string) int64 {
	fs,err := os.Stat(filepath)
	if err != nil {
		fmt.Println(err)
		return 0;
	}
	return fs.Size()
}

//创建文件夹
func mkOutputDir(root string) (string,error){
	//dirName := root+"/result/";
	dirName := root;
	_, err := os.Stat(dirName)
	if err == nil {
		return dirName, nil
	}
	if os.IsNotExist(err) {
		// 创建文件夹
		err := os.MkdirAll(dirName, os.ModePerm)
		if err != nil {
			return "",err
		} else {
			return dirName, nil
		}
	}
	return "", err
}


func Compress(fileName string,quality int,outputDir string) (string,error) {
	mkOutputDir(outputDir)


	file, err := os.Open(fileName)
	if err != nil {
		fmt.Println(err ,81)
		return "",err
	}
	defer file.Close()

	arr := strings.Split(fileName,"\\");
	baseName := arr[len(arr)-1]
	save := outputDir+"\\" + baseName;
	file1, err := os.Create(save)
	if err != nil {
		fmt.Println(err,93)
		return "",err
	}
	defer file1.Close()
	if quality >= 100 || quality == 0 {
		_,err := CopyImg(fileName,save)
		if err != nil {
			return "",err
		}
		return save,err
	}
	err = CompressImg(file,file1,quality)
	if err != nil {
		return "",err
	}
	return save,nil
}
//压缩图
func CompressImg(file io.Reader,file1 io.Writer,quality int) (error) {
	img, err := jpeg.Decode(file) //解码
	if err != nil {
		fmt.Println(err)
		return err
	}

	err = jpeg.Encode(file1, img, &jpeg.Options{quality})
	if err != nil {
		fmt.Println(err)
		return err
	}
	return nil
}

//复制图
func CopyImg(srcFile string,destFile string) (int64,error)  {
	file1,err:=os.Open(srcFile)
	if err != nil{
		return 0,err
	}
	file2,err:=os.OpenFile(destFile,os.O_WRONLY|os.O_CREATE,os.ModePerm)
	if err !=nil{
		return 0,err
	}
	defer file1.Close()
	defer file2.Close()

	return io.Copy(file2,file1)
}

//md5
func Md5(fileName string) string {

	fs, err := os.Open(fileName)
	if err != nil {
		fmt.Errorf("打开文件失败，filename=%v, err=%v", fileName, err)
		return ""
	}
	defer fs.Close()

	md5h := md5.New()
	io.Copy(md5h, fs)
	return hex.EncodeToString(md5h.Sum(nil))

}